#include "person.h"
#include "iostream"
#include <QStringList>
#include "fstream"

#include <iostream>

using namespace  std;

#define MAX_LINE_LENGTH 100
#define LOG_FILE_NAME "YouAreTheOne.log"


ID *ID::theID = NULL;

const QString Person::GenderStr[2] = {"Male", "Female"};

Person::Person(){
}
Person::Person(QString name = "", int age = 0, QString location = "", Gender g = MALE)
    :_id(ID::getID()),
      _name(name),
      _age(age),
      _location(location),
    _gender(g){

}

ostream& operator <<(ostream &os, Person &p){
    os << "ID:" << QString::number( p._id).toStdString() << "\n"
       << "\tName:" <<  p._name.toStdString() << "\n"
       << "\tAge:" << QString::number( p._age).toStdString() << "\n"
       << "\tLocation:" <<  p._location.toStdString() << "\n"
       <<"\tGender:" << p.GenderStr[p._gender].toStdString() << "\n";
    return os;
}

istream& operator >>(istream &is, Person &p){
     p._id =  p.getInfoFromIstream(is).toInt();
     p._name =  p.getInfoFromIstream(is);
     p._age =  p.getInfoFromIstream(is).toInt();
     p._location =  p.getInfoFromIstream(is);
     if(p.getInfoFromIstream(is) == Person::GenderStr[MALE]){
         p._gender = MALE;
     }else{
         p._gender = FEMALE;
     }
     return is;
}

QString Person::getInfoFromIstream(istream &is){
    char temp[MAX_LINE_LENGTH];
    is.getline(temp, MAX_LINE_LENGTH);
    QString str = QString::fromAscii(temp);
    QStringList strList = str.split(":");
    QString resultStr = strList.at(1);
    return resultStr;
}


void Person::save(){
    ofstream fs;
    fs.open(QString(LOG_FILE_NAME).append(QString::number(_id)).toAscii(), ios::out);
    fs << *this ;
    fs.close();
}

void Person::load(){
        ifstream is;
        is.open(QString(LOG_FILE_NAME).append(QString::number(_id)).toAscii());
        is >> *this;
        is.close();
}

void Person::outPut2Console(){
    cout << *this;
}
